import request from '@/utils/request';
import { RootThunkAction, HomeAction } from '@/types/store'
import { ApiResponse, Channel, ArticleRes } from '@/types/data'
import { hasToken, getChannels, setChannels } from '@/utils/storage'

// 获取用户频道
export function getUserChannel(): RootThunkAction {
  return async (dispatch, getState) => {
    // 判断是否登录
    if (hasToken()) {
      // 登录了
      const res = await request.get<ApiResponse<{ channels: Channel[] }>>('/user/channels')
      dispatch({
        type: 'home/saveUserChannels',
        payload: res.data.data.channels
      })
    } else {
      // 没有登录，优先从本地获取
      const channels = getChannels()
      if (channels.length > 0) {
        // 本地有数据
        dispatch({
          type: 'home/saveUserChannels',
          payload: channels
        })
      } else {
        // 本地没有数据，从网络获取，且存储到本地
        const res = await request.get<ApiResponse<{ channels: Channel[] }>>('/user/channels')
        dispatch({
          type: 'home/saveUserChannels',
          payload: res.data.data.channels
        })
        // 存储到本地
        setChannels(res.data.data.channels)
      }
    }
  }
}

// 获取所有频道
export function getAllChannel(): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    dispatch({
      type: 'home/saveAllChannels',
      payload: res.data.data.channels
    })
  }
}

/**
 * 修改高亮的方法
 * @param id
 * @returns
 */
export function changeActive(id: number): HomeAction {
  return {
    type: 'home/changeActive',
    payload: id
  }
}


// 添加频道
export function addChannel(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    // 获取到所有的userChannels
    const { userChannels } = getState().home
    // 如果登录了，发送请求获取频道信息
    if (hasToken()) {
      await request.patch('/user/channels', {
        channels: [{
          id: channel.id
        }]
      })
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setChannels([...userChannels, channel])
    }
    dispatch(getUserChannel())
  }
}

// 删除频道
export function delChannel(id: number): RootThunkAction {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 用户登录了，发送请求进行删除
      await request.delete('user/channels', {
        data: {
          channels: [id]
        }
      })
    } else {
      // 如果没有登录，本地删除一条数据
      setChannels(userChannels.filter(item => item.id !== id))
    }
    // 统一更新到redux
    dispatch(getUserChannel())
  }
}

/**
 * 获取文章列表
 * @param channel_id 获取文章列表
 * @param timestamp 时间戳
 * @returns
 */
export function getArticleList(
  channel_id: number,
  timestamp: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<ArticleRes>>('/articles', {
      params: {
        channel_id,
        timestamp
      }
    })
    const {
      pre_timestamp,
      results
    } = res.data.data
    dispatch({
      type: 'home/saveChannelArticles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      }
    })
  }
}

export function getNewArticleList(
  channel_id: number,
  timestamp: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<ArticleRes>>('/articles', {
      params: {
        channel_id,
        timestamp
      }
    })
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/saveNewChannelArticles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results
      }
    })
  }
}
